﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Activities;
using System.Diagnostics;

namespace TfsExtensions.Build.Activities
{
    public sealed class InvokeChmBuilder : CodeActivity
    {
        [RequiredArgument]
        public InArgument<string> SandcastleProductionToolsFolder { get; set; }

        [RequiredArgument]
        public InArgument<string> WorkingFolderName { get; set; }

        [RequiredArgument]
        public InArgument<string> SandcastleLocalLanguageCode { get; set; }
        
        [RequiredArgument]
        public InArgument<string> AppName { get; set; }

        [RequiredArgument]
        public InArgument<string> ChmFolderName { get; set; }

        // If your activity returns a value, derive from CodeActivity<TResult>
        // and return the value from the Execute method.
        protected override void Execute(CodeActivityContext context)
        {
            // This activity run following command
            //     <Exec Command="&quot;$(ChmBuilderEXE)&quot; /project:&quot;$(AppName)&quot; /html:&quot;$(WorkingFolderName)\html&quot; /lcid:$(SandcastleLocalLanguageCode) /toc:$(WorkingFolderName)\TOC.xml /out:&quot;$(ChmFolderName)&quot;" />

            var workingFolderName = this.WorkingFolderName.Get(context);

            var exeFileName = string.Format(@"{0}\ChmBuilder.exe", this.SandcastleProductionToolsFolder.Get(context));

            var projectName = "/project:\"" + string.Format("{0}", this.AppName.Get(context)) + "\"";

            var htmlWorkingFolderPath = "/html:\"" + string.Format(@"{0}\html", workingFolderName) + "\"";

            var sandcastleLanguageCode = "/lcid:" + string.Format("{0}", this.SandcastleLocalLanguageCode.Get(context));

            var tocWorkingFolderPath = "/toc:\"" + string.Format(@"{0}\TOC.xml", workingFolderName) + "\"";

            var outputPath = "\"" + string.Format("{0}", this.ChmFolderName.Get(context)) + "\"";

            var arguments = string.Format("{0} {1} {2} {3} /out:{4}", projectName, htmlWorkingFolderPath, sandcastleLanguageCode, tocWorkingFolderPath, outputPath);

            try
            {
                InvokeCommand.ExecuteCommand(context, exeFileName, arguments);
            }
            catch(Exception ex)
            {
                LogHelper.LogError(context, ex.Message);
                throw;
            }
        }
    }
}
